<template>
  <div>
    <div class="module-header">
      <div class="module-prompt f-left">题库</div>
      <el-button class="f-right" type="danger" size="small" @click="openDialog">新增考题</el-button>
    </div>
    <div class="header-search">
      <el-cascader
        size="small"
        placeholder="分类筛选"
        :options="options"
        v-model="category"
        :props="{checkStrictly: true}"
        change-on-select
        clearable
        @change="handleSearchChange"
      ></el-cascader>
      <el-input
        size="small"
        placeholder="请输入搜索内容"
        prefix-icon="el-icon-search"
        v-model="title"
        @change="handleSearchTitleChange"
        @keyup.enter.native="searchTitle()"
        style="margin-left: 10px; width: 24%;"
      ></el-input>
    </div>
    <el-table
      stripe
      ref="multipleTable"
      :data="questionList"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <el-table-column
        v-for="(data,index) in questionOpts"
        :key="index"
        :prop="data.field"
        :label="data.th"
        :formatter="data.format"
        align="center"
        :show-overflow-tooltip="true"
        :width="data.width"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="140">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="mini" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row :gutter="20" class="p-t-10" v-if="pageCount>1">
      <el-col :span="10" :offset="14">
        <el-pagination
          class="f-right"
          @current-change="handleCurrentChange"
          :current-page.sync="searchObj.page"
          :page-size="searchObj.size"
          :page-count="pageCount"
          background
          layout="total,prev, pager, next"
          :total="totals"
        ></el-pagination>
      </el-col>
    </el-row>
    <el-dialog
      :title="'考题' + (mode=='add' ? '录入' : '编辑')"
      width="70%"
      :visible.sync="dialogVisible"
    >
      <div class="over-hid">
        <!-- <div>{{questionObj.options}}</div> -->
        <v-input sm="24" label="选择题型">
          <el-radio
            v-model="questionObj.type"
            :label="item.val"
            v-for="(item,index) in examTypeList"
            :key="index"
          >{{item.label}}</el-radio>
        </v-input>
        <v-input sm="24" label="题目录入">
          <el-row :gutter="20" class="p-t-10">
            <el-col class="full-width" :span="20">
              <div class="question-box">
                <el-input
                  type="textarea"
                  size="mini"
                  autosize
                  placeholder="请输入问题"
                  v-model="questionObj.body.title"
                ></el-input>
                <v-single-img
                  v-if="questionObj.body.imgSrc!==undefined"
                  size="small"
                  :img.sync="questionObj.body.imgSrc"
                ></v-single-img>
                <v-single-audio
                  v-if="questionObj.body.audioSrc!==undefined"
                  size="small"
                  :img.sync="questionObj.body.audioSrc"
                ></v-single-audio>
                <v-single-video
                  v-if="questionObj.body.videoSrc!==undefined"
                  size="small"
                  :img.sync="questionObj.body.videoSrc"
                ></v-single-video>
              </div>
            </el-col>
            <el-col :span="4">
              <div class="align-center question-opt">
                <el-button
                  size="mini"
                  type="success"
                  icon="iconfont icon-tupian"
                  @click="setQuestionTitle('img')"
                ></el-button>
              </div>
              <div class="align-center question-opt">
                <el-button
                  size="mini"
                  type="success"
                  icon="iconfont icon-yinpin"
                  @click="setQuestionTitle('audio')"
                ></el-button>
              </div>
              <div class="align-center question-opt">
                <el-button
                  size="mini"
                  type="success"
                  icon="iconfont icon-shexiangji"
                  @click="setQuestionTitle('video')"
                ></el-button>
              </div>
              <div class="align-center question-opt">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="setQuestionTitle('del')"
                ></el-button>
              </div>
            </el-col>
          </el-row>
        </v-input>
        <v-input sm="24" label="选项设置" v-if="questionObj.type<3">
          <div class="m-b-10" v-for="(tag,index) in questionObj.options" :key="index">
            <el-tag
              :key="tag"
              closable
              size="medium"
              :disable-transitions="false"
              @close="handleOptClose(index)"
            >{{tag}}</el-tag>
          </div>
          <el-input
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="mini"
            @keyup.enter.native="handleInputConfirm"
          ></el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="inputVisible = true"
          >+ New Option</el-button>
        </v-input>
        <v-input sm="24" label="答案设置" v-if="questionObj.type<4">
          <div v-if="questionObj.type == 1">
            <div class="m-b-10" v-for="(item,index) in questionObj.options" :key="index">
              <el-radio v-model="questionObj.answer" :label="index" :key="index">{{item}}</el-radio>
            </div>
          </div>
          <el-checkbox-group v-if="questionObj.type == 2" v-model="questionObj.answer" size="mini">
            <div class="m-b-10" v-for="(item,index) in questionObj.options" :key="index">
              <el-checkbox :label="item" :key="item">{{item}}</el-checkbox>
            </div>
          </el-checkbox-group>
          <el-switch
            v-if="questionObj.type == 3"
            v-model="questionObj.answer"
            active-color="#13ce66"
          ></el-switch>
        </v-input>
        <!--新增填空题-->
        <v-input sm="24" label="答案设置" v-if="questionObj.type==4">
          <div class="m-b-10" v-for="(tag,index) in questionObj.answer" :key="index">
            <el-tag
              :key="tag"
              closable
              size="medium"
              :disable-transitions="false"
              @close="handleGapClose(index)"
            >{{tag}}</el-tag>
          </div>
          <el-input
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="mini"
            @keyup.enter.native="handleGapInputConfirm"
          ></el-input>
          <el-button
            v-else
            class="button-new-tag"
            size="small"
            @click="inputVisible = true"
          >+ New Option</el-button>
        </v-input>

        <!--ccend-->

        <v-input sm="20" label="题目详解">
          <el-input
            size="mini"
            type="textarea"
            :rows="2"
            placeholder="题目详解"
            v-model="questionObj.explanation"
          ></el-input>
        </v-input>
        <v-input sm="24" label="类型选择">
          <el-tag
            class="m-b-10"
            v-for="(item,index) in questionObj.categoryInfo"
            :key="item"
            closable
            @close="handleLabelClose(index)"
          >{{item}}</el-tag>
          <div>
            <el-cascader
              size="mini"
              :options="optionSel"
              v-model="category1"
              @change="handleChange"
            ></el-cascader>
          </div>
        </v-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">关闭</el-button>
        <el-button
          size="small"
          type="danger"
          @click="mode == 'add' ? addQuestion() : editQuestion()"
        >{{mode == "add" ? "新增考题" : "更新考题"}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { vInput, vSingleImg, vSingleAudio, vSingleVideo } from "vHome";
import { userService } from "api";
import { questionOpts } from "./question";
export default {
  components: {
    vInput,
    vSingleImg,
    vSingleAudio,
    vSingleVideo
  },
  data() {
    return {
      questionOpts,
      questionList: [],
      searchObj: {
        page: 1,
        size: 8
      },
      pageCount: 0,
      questionObj: {
        body: {},
        options: [],
        answer: [],
        category: [],
        categoryInfo: []
      },
      dialogVisible: false,
      mode: "add",
      examTypeList: [
        { label: "单选题", val: 1 },
        { label: "多选题", val: 2 },
        { label: "判断题", val: 3 },
        { label: "填空题", val: 4 }
      ],
      inputVisible: false,
      inputValue: "",
      options: [],
      optionSel: [],
      labelTypeList: ["", "success", "info", "warning", "danger"],
      refreshList: 0,
      refreshList1: 0,
      refreshList2: 0,
      refreshList3: 0,
      totals: 0,
      category: [],
      category1: [],
      categorySearchObj: {
        page: 1,
        size: 8
      },
      categoryId: "",
      categoryName: "",
      title: "",
      quesType: "",
      categoryService: []
    };
  },
  methods: {
    setQuestionTitle(type) {
      switch (type) {
        case "img":
          // delete this.questionObj.body.audioSrc;
          // delete this.questionObj.body.videoSrc;
          this.questionObj.body = {
            title: this.questionObj.body.title,
            imgSrc: ""
          };
          break;
        case "audio":
          // delete this.questionObj.body.imgSrc;
          // delete this.questionObj.body.videoSrc;
          this.questionObj.body = {
            title: this.questionObj.body.title,
            audioSrc: ""
          };
          break;
        case "video":
          // delete this.questionObj.body.imgSrc;
          // delete this.questionObj.body.audioSrc;
          this.questionObj.body = {
            title: this.questionObj.body.title,
            videoSrc: ""
          };
          break;
        case "del":
          // delete this.questionObj.body.imgSrc;
          // delete this.questionObj.body.audioSrc;
          // delete this.questionObj.body.videoSrc;
          this.questionObj.body = {
            title: this.questionObj.body.title
          };
          break;
      }
      // this.questionObj.body+=" "
      // this.$set(this.questionObj,"body",this.questionObj.body)
    },
    //题目搜索选项改变
    handleCurrentChange() {
      if (this.categoryId) {
        this.categorySearchObj.page = this.searchObj.page;
        this.categorySearchObj.size = this.searchObj.size;
        this.refreshList1++;
      } else if (this.title) {
        this.categorySearchObj.page = this.searchObj.page;
        this.categorySearchObj.size = this.searchObj.size;
        this.refreshList2++;
      } else if (this.categoryName && this.category.length != 0) {
        this.categorySearchObj.page = this.searchObj.page;
        this.categorySearchObj.size = this.searchObj.size;
        this.refreshList1++;
      } else {
        this.refreshList++;
      }
    },
    getCategoryList() {
      userService.getCategoryList().then(res => {
        let categoryList = res;
        let options = [];
        categoryList.forEach((item, index) => {
          let children = [];
          if (item.children) {
            item.children.forEach((item1, index1) => {
              userService.getTypeByCategory(item1.id).then(res => {
                if (res.length != 0) {
                  let child = [];
                  res.forEach((item2, index2) => {
                    if (item2.type == 1) {
                      child.push({
                        value: item2.type,
                        label: "单选题",
                        type: item2.type
                      });
                    }
                    if (item2.type == 2) {
                      child.push({
                        value: item2.type,
                        label: "多选题",
                        type: item2.type
                      });
                    }
                    if (item2.type == 3) {
                      child.push({
                        value: item2.type,
                        label: "判断题",
                        type: item2.type
                      });
                    }
                  });
                  children.push({
                    value: item1.id,
                    //label: item1.name +"(" + item1.question + ")",
                    label: item1.name,
                    // label: item1.name +"(" + aa + ")",
                    id: item1.id,
                    children: child
                  });
                }
              });
            });
          }
          options.push({
            value: item.name,
            //label: item.name +"(" + item.question + ")",
            label: item.name,
            children: children,
            id: item.id
          });
        });
        this.options = options;
      });
    },
    //新增编辑题目时类型选择
    getCategoryListNotSel() {
      userService.getCategoryList().then(res1 => {
        let categoryList1 = res1;
        let options1 = [];
        categoryList1.forEach((item3, index3) => {
          let children1 = [];
          if (item3.children) {
            item3.children.forEach((item4, index4) => {
              children1.push({
                value: index4,
                label: item4.name,
                id: item4.id
              });
            });
          }
          options1.push({
            value: index3,
            label: item3.name,
            children: children1,
            id: item3.id
          });
        });
        this.optionSel = options1;
      });
    },
    getQuestionList() {
      let obj = {
        page: this.searchObj.page - 1,
        size: this.searchObj.size
      };
      if (this.categoryId == "") {
        userService.getQuestionList(obj).then(res => {
          this.questionList = res.content;
          this.pageCount = res.totalPages;
          this.totals = res.totalElements;
          // res.content.forEach(item => {
          // 	if(JSON.parse(item.body).length){
          // 		console.log(item.body)
          // 	}
          // })
          // return
        });
      } else {
        this.getQuestionListByCategory();
      }
    },
    addQuestion() {
      // return console.log(this.questionObj)

      let obj = clone(this.questionObj);
      if (!obj.body.title)
        return this.$notify({
          message: "请填写试题名称！",
          type: "warning"
        });
      if (!obj.type)
        return this.$notify({
          message: "请选择试题类型！",
          type: "warning"
        });
      obj.body = JSON.stringify(obj.body);
      obj.options.forEach((item, index) => {
        obj.options[index] = item.trim();
      });
      obj.answer =
        typeof obj.answer == "object"
          ? JSON.stringify(obj.answer.sort())
          : obj.answer;
      userService.addQuestion(obj).then(res => {
        this.$notify({
          message: "新增成功！",
          type: "success"
        });
        this.dialogVisible = false;
        this.refreshList++;
      });
    },
    editQuestion() {
       debugger;

      let obj = clone(this.questionObj);
     
      if (!obj.body.title)
        return this.$notify({
          message: "请填写试题名称！",
          type: "warning"
        });
      if (!obj.type)
        return this.$notify({
          message: "请选择试题类型！",
          type: "warning"
        });
      obj.body = JSON.stringify(obj.body);
     // if(obj.type==1||obj.type==2){
       // obj.answer=
      //}
      obj.answer =
        typeof obj.answer == "object"
          ? JSON.stringify(obj.answer.sort())
          : obj.answer;
      obj.options.forEach((item, index) => {
        obj.options[index] = item.trim();
      });
      userService.editQuestion(obj.id, obj).then(res => {
        this.$notify({
          message: "编辑成功！",
          type: "success"
        });
        this.dialogVisible = false;
        this.refreshList++;
        this.getCategoryList();
      });
    },
    handleSearchChange(value) {
      debugger;
      this.searchObj.page = 1;
      if (value.length == 0) {
        this.categoryId = "";
        this.searchType = 2;
        return this.refreshList++;
      } else {
        this.categorySearchObj.page = 1;
        let id = 0;
        let cateName = "";
        let type1 = 0;
        if (value.length == 1) {
          cateName = value[0];
          this.categoryName = cateName + "/";
          this.searchType = 3;
        } else if (value.length == 2) {
          id = value[1];
          this.categoryId = id;
          this.searchType = 4;
        } else if (value.length == 3) {
          id = value[1];
          type1 = value[2];
          this.categoryId = id;
          this.quesType = type1;
          this.searchType = 5;
        }
        return this.refreshList1++;
      }
    },
    handleSearchTitleChange(value) {
      this.searchObj.page = 1;
      if (value.length == 0 && this.categoryId == "") {
        //无分类搜索
        this.title = "";
        this.searchType = 2;
        return this.refreshList++;
      } else {
        this.categorySearchObj.page = 1;
        this.title = value;
        return this.refreshList2++;
      }
    },
    getQuestionListByCategory() {
      let obj = {
        page: this.categorySearchObj.page - 1,
        size: this.categorySearchObj.size
      };
      /** userService.getQuestionListByCategory(this.categoryId, obj).then(res => {
        this.questionList = res.content;
        this.pageCount = res.totalPages;
      });*/
      if (this.searchType == 3) {
        debugger;
        console.log(this.categoryName);
        userService
          .getQuestionListByCategoryName(this.categoryName, obj)
          .then(res => {
            this.questionList = res.content;
            this.pageCount = res.totalPages;
            this.totals = res.totalElements;
          });
      } else if (this.searchType == 4) {
        userService
          .getQuestionListByCategory(this.categoryId, obj)
          .then(res => {
            this.questionList = res.content;
            this.pageCount = res.totalPages;
            this.totals = res.totalElements;
          });
      } else if (this.searchType == 5) {
        userService
          .getQuetionListByType(this.quesType, this.categoryId, obj)
          .then(res => {
            this.questionList = res.content;
            this.pageCount = res.totalPages;
            this.totals = res.totalElements;
          });
      }
    },
    searchTitle() {
      let obj = {
        page: this.categorySearchObj.page - 1,
        size: this.categorySearchObj.size
      };
      userService.getQuestionListByTitle(this.title, obj).then(res => {
        this.questionList = res.content;
        this.pageCount = res.totalPages;
        this.totals = res.totalElements;
      });
    },
    handleChange(value) {
      this.questionObj.categoryInfo.push(
        this.optionSel[value[0]].label +
          "/" +
          this.optionSel[value[0]].children[value[1]].label
      );
      this.questionObj.category.push(
        this.optionSel[value[0]].children[value[1]].id
      );
    },
    getLabelType() {},
    addQuestionContent(type) {
      this.questionObj.body.push({ type: type, val: "" });
    },
    openDialog() {
      this.dialogVisible = true;
      this.mode = "add";
      this.questionObj = {
        body: {},
        options: [],
        answer: [],
        category: [],
        categoryInfo: []
      };
    },
    handleEdit(row) {
      debugger;
      let obj = clone(row);
      obj.body = JSON.parse(obj.body);
      obj.answer = JSON.parse(obj.answer);
      this.questionObj = obj;
      this.mode = "edit";
      this.dialogVisible = true;
    },
    handleDel(row) {
      this.$confirm("此操作将删除该题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          userService.delQuestion(row.id).then(res => {
            this.refreshList++;
            this.$notify({
              message: "删除成功！",
              type: "success"
            });
            //this.getCategoryList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    delQuestion() {
      this.questionObj.answer = [];
    },
    handleInputConfirm() {
      this.questionObj.options.push(this.inputValue);
      this.inputValue = "";
      this.inputVisible = true;
    },
    handleOptClose(index) {
      this.questionObj.options.splice(index, 1);
    },
    //填空题
    handleGapInputConfirm() {
      debugger;
      this.questionObj.answer.push(this.inputValue);
      this.inputValue = "";
      this.inputVisible = true;
    },
    handleGapClose(index) {
      this.questionObj.answer.splice(index, 1);
    },
    //填空题end
    handleLabelClose(index) {
      this.questionObj.categoryInfo.splice(index, 1);
      this.questionObj.category.splice(index, 1);
    }
  },
  mounted() {
    this.refreshList++;
    this.getCategoryListNotSel();
    this.getCategoryList();
  },
  watch: {
    refreshList: "getQuestionList",
    refreshList1: "getQuestionListByCategory",
    refreshList2: "searchTitle",
    "questionObj.type": function() {
      this.questionObj.answer = [];
    }
  }
};
</script>
<style scoped>
.question-opt {
  padding-bottom: 10px;
}

.full-width {
  min-height: 10px;
}

.question-box > div {
  margin-bottom: 10px;
}
.header-search {
  display: flex;
  justify-content: start;
  align-items: center;
}
</style>
